# -*- coding: utf-8 -*-
from mdMySpi import *
import thostmduserapi as MDapi
import configparser
import threading
import os

#local config check check
if(os.path.exists("config.local.ini")):
	configfile = "config.local.ini"
else:
	configfile = "config.ini"


configins=configparser.ConfigParser()
configins.read(configfile)
#Addr
FrontAddr=configins['network']['mdfront']
#AuthInfo
APPID=configins['authinfo']['appid']
AUTHCODE=configins['authinfo']['authcode']
#LoginInfo
BROKERID=configins['baseinfo']['brokerid']
USERID=configins['baseinfo']['userid']
PASSWORD=configins['baseinfo']['password']
#search conf
TIMEOUTSEC=int(configins['searchopt']['timeoutsec'])
#mddata
mdlist=configins['ReqDepthMD']['mdlist'].split(',')



class CMDApi(MDapi.CThostFtdcMdApi):
    def __init__(self):
        self.mdspi=''
        self.mdapi=''
        self.ctlevent=threading.Event()
        self.mdlist=mdlist

    def start(self):
        self.mdapi=MDapi.CThostFtdcMdApi.CreateFtdcMdApi()
        self.mdspi=CFtdcMdSpi(self)
        self.mdapi.RegisterFront(FrontAddr)
        self.mdapi.RegisterSpi(self.mdspi)
        self.mdapi.Init()
        self.ctlevent.wait(timeout = TIMEOUTSEC)
        if(self.ctlevent.isSet() == True):
            self.ctlevent.clear()
            return 0
        else:
            print("init failed, please check network env")
            return 233
            os._exit(233)
    
    def ReqLogin(self):
        loginfield = MDapi.CThostFtdcReqUserLoginField()
        loginfield.BrokerID=BROKERID
        loginfield.UserID=USERID
        loginfield.Password=PASSWORD
        loginfield.UserProductInfo="python dll"
        self.mdapi.ReqUserLogin(loginfield,0)
        PrintSendName("ReqUserLogin")
        self.ctlevent.wait(timeout = TIMEOUTSEC)
        if(self.ctlevent.isSet() == True):
            self.ctlevent.clear()
            return 0
        else:
            return 233
            os._exit(233)
    
    def ReqDepthMD(self):
        for i in range(len(self.mdlist)):
            self.mdlist[i]=self.mdlist[i].encode('utf-8')
        ret=self.mdapi.SubscribeMarketData(self.mdlist, len(self.mdlist))
        PrintSendName("SubscribeMarketData")
        self.ctlevent.wait()
    
    def ReqTraDay(self):
        currday = self.mdapi.GetTradingDay()
        return currday


#print func name
def PrintSendName(sendname):
    sendmsg = "send " + sendname + " ok"
